package com.xhu.collegestudentrentalsystem.module.user.controller;

import com.xhu.collegestudentrentalsystem.annocation.LoginRequired;
import com.xhu.collegestudentrentalsystem.module.user.entity.Comment;
import com.xhu.collegestudentrentalsystem.module.user.entity.DiscussPost;
import com.xhu.collegestudentrentalsystem.module.user.entity.Page;
import com.xhu.collegestudentrentalsystem.module.user.entity.User;
import com.xhu.collegestudentrentalsystem.module.user.service.impl.DiscussPostServiceImpl;
import com.xhu.collegestudentrentalsystem.util.HostHolder;
import com.xhu.collegestudentrentalsystem.util.ResultData;
import com.xhu.collegestudentrentalsystem.util.constant.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhu huilin
 * @date 2023/4/2 10:22
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController {

    @Autowired
    private DiscussPostServiceImpl discussPostService;

    @Autowired
    private HostHolder hostHolder;

    /**
     * 点击用户交流区，显示帖子内容（默认最新），使用逻辑分页实现
     *      最新帖子排序：置顶 > 时间 > 精华
     *      最热帖子排序：点赞/回复数 > 时间
     */
    @RequestMapping("/discussList")
    public String discussList(Page page, Integer hotPost, Model model){
        if(hotPost == null){
            hotPost = 0;
        }
        page.setLimit(6);
        List<DiscussPost> discussPosts = discussPostService.findDiscussPostByUserId(page, hotPost);
        model.addAttribute(KeyMsg.discussPost.DISCUSS_POST_LIST, discussPosts);
        if(hotPost == 1){
            model.addAttribute(KeyMsg.HOT_IS_LIGHT, true);
        }else {
            model.addAttribute(KeyMsg.HOT_IS_LIGHT, false);
        }
        page.setPath("/discuss/discussList?hotPost=" + hotPost);
        return "site/discuss";
    }

    /**
     * 用户发布新贴内容
     */
    @RequestMapping("/addDiscussPost")
    @ResponseBody
    public ResultData addDiscussPost(String title, String content){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        Integer result = discussPostService.addDiscussPost(title, content, hostHolder.getUser().getId());
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.news.ADD_SUCCESS);
        }
        return new ResultData(ResultData.OPERATION_FAIL, PointMsg.news.ADD_FAIL);
    }

    /**
     * 点击查看帖子详情
     */
    @RequestMapping("/detail/{discussPostId}")
    public String postDetail(@PathVariable("discussPostId") Long discussPostId, Page page, Model model){
        /*
            业务需求：1、根据帖子id查询帖子的信息
                    2、查询帖子所有的评论，分页显示
                    3、查询评论信息的回复
                    4、如果帖子不存在或已被删除（直接通过地址栏访问），直接转到帖子列表页面
         */
        page.setLimit(6);
        DiscussPost discussPost = discussPostService.findDiscussPostById(discussPostId, page);
        if(discussPost == null){
            model.addAttribute(KeyMsg.ERROR_MSG, PointMsg.discussPost.POST_NOT_EXIST);
            return "error/404";
        }
        model.addAttribute(KeyMsg.discussPost.DISCUSS_POST, discussPost);
        return "site/discuss-detail";
    }

    /**
     * 回复帖子信息
     */
    @LoginRequired
    @RequestMapping("/comment/add/{discussPostId}")
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment){
        if(comment.getContent() != null && !EnumProperty.EMPTY_STRING.equals(comment.getContent())){
            comment.setUserId(hostHolder.getUser().getId());
            comment.setStatus(StatusMsg.commentStatus.NORMAL);
            comment.setCreateTime(new Date());
            discussPostService.addComment(comment);
        }
        return "redirect:/discuss/detail/"+ discussPostId;
    }

    /**
     * 管理员删除帖子信息（只需要将状态修改为2拉黑/删除即可，包括删除回复表中的内容）
     */
    @RequestMapping("/deleteDiscussPost")
    @ResponseBody
    public ResultData deleteDiscussPost(Long discussPostId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        Integer result = discussPostService.updateDiscussPostStatus(discussPostId, StatusMsg.postStatus.BLOCK);
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.delete.DELETE_SUCCESS);
        }
        return new ResultData(ResultData.OPERATION_FAIL, PointMsg.delete.DELETE_FAIL);
    }

    /**
     * 管理员置顶帖子，修改帖子类型
     *      点击一次为置顶，修改按钮为“取消置顶”；
     *      再次点击为取消置顶，修改按钮为“置顶”。
     */
    @RequestMapping("/top")
    @ResponseBody
    public ResultData topDiscussPost(Long discussPostId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        DiscussPost post= discussPostService.updateDiscussPostType(discussPostId);
        if(post != null){
            ResultData resultData = new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.operation.OPERATION_SUCCESS);
            resultData.put(KeyMsg.discussPost.DISCUSS_POST_TYPE, post.getPostType());
            return resultData;
        }
        return new ResultData(ResultData.OPERATION_FAIL, PointMsg.operation.OPERATION_FAIL);
    }

    /**
     * 管理员将帖子置为精华（类似于置顶，但修改的是状态）
     */
    @RequestMapping("/cream")
    @ResponseBody
    public ResultData creamDiscussPost(Long discussPostId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        DiscussPost post = discussPostService.updateDiscussPostCream(discussPostId);
        if(post != null){
            ResultData resultData = new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.operation.OPERATION_SUCCESS);
            resultData.put(KeyMsg.discussPost.DISCUSS_POST_STATUS, post.getPostStatus());
            return resultData;
        }
        return new ResultData(ResultData.OPERATION_FAIL, PointMsg.operation.OPERATION_FAIL);
    }

    /**
     * 点赞
     */
    @RequestMapping("/like")
    @ResponseBody
    public ResultData userLike(Long entityId, Integer entityType){
        User user = hostHolder.getUser();
        if(user == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        discussPostService.like(entityId, entityType, user.getId());
        // 查询帖子或评论的点赞数量和状态，封装返回
        Long likeCount = discussPostService.findLikeCount(entityId, entityType);
        Integer likeStatus = discussPostService.findLikeStatus(entityId, entityType, user.getId());
        ResultData resultData = new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.operation.OPERATION_SUCCESS);
        resultData.put(KeyMsg.LIKE_COUNT, likeCount);
        resultData.put(KeyMsg.LIKE_STATUS, likeStatus);
        return resultData;
    }

    /**
     * 根据关键词查询帖子信息
     */
    @RequestMapping("/searchPost")
    public String searchPost(Page page, String keyword, Model model){
        page.setLimit(6);
        List<DiscussPost> discussPosts = discussPostService.findDiscussPostByKeyword(page, keyword);
        model.addAttribute(KeyMsg.discussPost.DISCUSS_POST_LIST, discussPosts);
        model.addAttribute(KeyMsg.HOT_IS_LIGHT, false);
        model.addAttribute(KeyMsg.KEY_WORD, keyword);
        page.setPath("/discuss/searchPost");
        return "site/discuss";
    }
}
